package org.oneblog.data.util;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Smile.Wu
 * @date 2016年4月14日  下午2:42:30
 */
public class QueryStringBuilder {

    private List<String> subQuerys = new ArrayList<String>();

    public int subQuerySize() {
        return subQuerys.size();
    }

    public QueryStringBuilder(String subQuery) {
        addSubQuery(subQuery);
    }

    public QueryStringBuilder() {
    }

    public QueryStringBuilder addSubQuery(String subQuery) {
        if (StringTools.isNotBlank(subQuery) && subQuery.indexOf(':') > 0) {
            subQuerys.add(subQuery.trim());
        }
        return this;
    }

    public QueryStringBuilder addSubQuery(String field, Object value) {
        if (value != null && String.valueOf(value).length() > 0) {
            addSubQuery(field + ":" + value.toString());
        }
        return this;
    }

    public QueryStringBuilder addSubQuery(String field, Object value, int weight) {
        if (value != null && String.valueOf(value).length() > 0) {
            addSubQuery(field + ":" + value.toString() + "^" + weight);
        }
        return this;
    }

    public String buildAndQueryString() {
        return buildQueryString(" AND ");
    }

    public String buildOrQueryString() {
        return buildQueryString(" OR ");
    }

    private String buildQueryString(String operator) {
        StringBuilder query = new StringBuilder("");
        if (subQuerys.size() > 0) {
            String sub = subQuerys.remove(0).trim();
            if(sub.toUpperCase().startsWith("NOT")) {
                query.append(" " + sub + " ");
            } else {
                query.append("( " + sub + " )");
            }
            if (subQuerys.size() > 0) {
                for (String sq : subQuerys) {
                    sub = sq.trim();
                    if(sub.toUpperCase().startsWith("NOT")) {
                        query.append(operator).append(" " + sq + " ");
                    } else {
                        query.append(operator).append("( " + sq + " )");
                    }
                }
            }
        }
        if (query.length() < 2) {
            return "";
        }
        return "(" + query.toString() + ")";
    }

    public static QueryStringBuilder create(String field, Object value, int weight) {
        QueryStringBuilder temp = new QueryStringBuilder();
        temp.addSubQuery(field, value, weight);
        return temp;
    }

    public static QueryStringBuilder create(String subQuery) {
        QueryStringBuilder temp = new QueryStringBuilder(subQuery);
        return temp;
    }

    public static QueryStringBuilder create(String field, Object value) {
        QueryStringBuilder temp = new QueryStringBuilder();
        temp.addSubQuery(field, value);
        return temp;
    }
}
